package com.tanhua.dubbo.api.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.domain.db.Announcement;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.MessagesApi;
import com.tanhua.dubbo.mapper.AnnouncementMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class MessagesApiImpl implements MessagesApi {

    @Autowired
    private AnnouncementMapper announcementMapper;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查找所有公告数据
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public IPage<Announcement> findAll(Integer page, Integer pageSize) {

        IPage<Announcement> iPage = new Page<>(page, pageSize);

        return announcementMapper.findAll(iPage);
    }

    /**
     * 点赞、喜欢、评论列表
     *
     * @return
     */
    @Override
    public PageResult likes(Long userId, Integer commentType, Integer page, Integer pagesize) {

        // 创建查询对象
        //评论类型，1-点赞，2-评论，3-喜欢
        Query query = new Query(
                Criteria.where("commentType").is(commentType)
                        .and("publishUserId").is(userId)
        );
        query.with(Sort.by(Sort.Order.desc("created")));
        query.skip((page - 1) * pagesize).limit(pagesize);

        // 查询
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        long count = mongoTemplate.count(query, Comment.class);

        return new PageResult(page, pagesize, (int) count, comments);
    }
}
